<?php
namespace App\Http\Requests;

use App\Exceptions\ApiException;
use Dingo\Api\Contract\Http\Request;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Http\FormRequest as IlluminateFormRequest;
class BaseFormRequest extends IlluminateFormRequest
{
    /**
     * 路由校验
     * Handle a failed validation attempt.
     *
     * @param \Illuminate\Contracts\Validation\Validator $validator
     *
     * @return void
     */
    protected function failedValidation(Validator $validator)
    {
        if  ($this->container['request']  instanceof Request) {
            $errors =$validator->errors()->getMessages();
            $message = '';
            foreach ($errors as $key =>  $value ){
                $message.=$key.':'.$value[0].',';
            }
            throw new ApiException($message);
        }
            // parent::failedValidation($validator);
        $a =  (new ValidationException($validator))
            ->errorBag($this->errorBag)
            ->redirectTo($this->getRedirectUrl());
          throw  new  ApiException(json_encode($a->getMessage()));

    }


    /**
     * Handle a failed authorization attempt.
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    protected function failedAuthorization()
    {
        if ($this->container['request'] instanceof Request) {
            throw new HttpException(403);
        }

        parent::failedAuthorization();
    }

}
